package com.ytjj.qmyx.users.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

@Slf4j
public class SmsWayUtil {
    private static final String ACCOUNT="xxxx";
    private static final String PASSWORD="xxxxx";
//    private static final String SEND_URL="http://api.smsway.com.cn/api/send";
    private static final String SEND_URL="http://api.smsway.com.cn:8070/api/send/sendsms";

    /**
     * 发信发送的目的号码.多个号码之间用半角逗号隔开,最多500个号码
     * @param mobile
     * @param content
     * @return
     */
    public static JSONObject sendSmsWithResult(String mobile,String content) {
        StringBuilder sb = new StringBuilder();
        sb.append("apiAccount="+ACCOUNT);
        sb.append("&secretKey="+PASSWORD);
        sb.append("&content="+content);
        sb.append("&mobiles="+mobile);
        String result=sendPostFormUrl(SEND_URL,sb.toString());
        log.info("sendSmsWithResult,result={}",result);
        return JSON.parseObject(result);
    }

    public static String sendPostFormUrl(String url, String param) {
        log.info("sendData:" + param);
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.error("Exception:" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        log.info("result:" + result);
        return result;

    }
}
